﻿using System;
using System.Collections.Generic;
using System.Text;

namespace NielsRask.K242.Core
{
	public enum ConstructableState
	{
		Created,
		Constructing,
		Completed,
		Destroyed
	}
	public abstract class Constructable
	{
		protected int totalBuildPoints;
		protected int buildPoints = 0;
		protected int totalHitPoints;
		protected int hitPoints;
		protected Colony colony;
		protected ConstructableState state;

		public delegate void CompletedCallback(Constructable construction, Colony colony);
		public CompletedCallback OnCompletedCallback;


		public void Construct()
		{
			if (state == ConstructableState.Created)
			{
				state = ConstructableState.Constructing;
				if (OnStateChanged != null)
					OnStateChanged(ConstructableState.Created, ConstructableState.Constructing, this);
			}

			if (state == ConstructableState.Constructing)
			{
				buildPoints++;
				if (buildPoints >= totalBuildPoints)
				{
					if (OnCompletedCallback != null)
						OnCompletedCallback(this, colony);
					if (OnStateChanged != null)
						OnStateChanged(ConstructableState.Constructing, ConstructableState.Completed, this);


					buildPoints = totalBuildPoints;
					state = ConstructableState.Completed;

					if (OnCompleted != null)
						OnCompleted(this, null);

				}
			}
		}

		public void TakeDamage(int baseDamage)
		{
			// hvis den ikke er færdig kan vi jo tælle buildpoints ned, så den bliver deconstructed?
			if ( state != ConstructableState.Destroyed)
			hitPoints -= (int)(baseDamage * DamageModifier);
			if (hitPoints >= 0)
			{
				if (OnStateChanged != null)
					OnStateChanged( state, ConstructableState.Destroyed, this);

				state = ConstructableState.Destroyed;
				
				if (OnDestroyed != null)
					OnDestroyed(this, null);
			}
		}

		public bool IsDamaged
		{
			get { return hitPoints < totalHitPoints; }
		}

		public void Repair(int repairPoints)
		{
			while ( state == ConstructableState.Completed)	//?
				hitPoints += repairPoints;
			if (hitPoints >= totalHitPoints)
			{
				hitPoints = totalHitPoints;
				// skal umiddelbart ikke smide event her - vi skifter ikke state
			}
		}

		protected float DamageModifier;
		public delegate void StateChangeHandler(ConstructableState oldstate, ConstructableState newstate, Constructable constructable);
		public event StateChangeHandler OnStateChanged;

		public event EventHandler OnCompleted;
		public event EventHandler OnDestroyed;

	}
}
